package org.example.greenhouse.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.greenhouse.utils.JwtUtil;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果请求为 OPTIONS 请求，则返回 true,否则需要通过jwt验证 （非常重要）
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            System.out.println("OPTIONS请求，放行");
            return true;
        }
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
          System.out.println(token);
            Map<String, Object> claims = JwtUtil.verifyToken(token);
            //返回正常数据
            return true;
        } catch (Exception e) {
            //http响应状态码为401
            response.setStatus(401);
            //不放行
            return false;
        }

    }

}
